package com.base.data.controller;

import androidx.collection.SparseArrayCompat;

import com.base.common.utils.UIUtils;
import com.base.common.viewmodel.RxSchedulerTransformer;
import com.base.data.model.sqlBean.GiveLikeBean;
import com.base.data.tools.SqliteUtils;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

public class GiveLikeModel {
    private GiveLikeModel() {
    }

    private static GiveLikeModel giveLikeModel;

    public static synchronized GiveLikeModel getInstance() {
        if (giveLikeModel == null) giveLikeModel = new GiveLikeModel();
        return giveLikeModel;
    }


    public SparseArrayCompat<GiveLikeBean> getList() {
        SparseArrayCompat<GiveLikeBean> sparseArrayCompat = new SparseArrayCompat<>();
        List<GiveLikeBean> listLikeBean = GiveLikeBean.listAll(GiveLikeBean.class);
        if (!UIUtils.isEmpty(listLikeBean)) {
            for (GiveLikeBean giveLikeBean : listLikeBean) {
                sparseArrayCompat.put(giveLikeBean.getBeanId(), giveLikeBean);
            }
        }
        return sparseArrayCompat;
    }


    public GiveLikeBean findByBeanId(int beanId) {
        List<GiveLikeBean> list = GiveLikeBean.find(GiveLikeBean.class, SqliteUtils.toSQLNameDefault("beanId") + "=?", String.valueOf(beanId));
        if (list.isEmpty()) return null;
        return list.get(0);
    }

    /**
     * 异步获取
     *
     * @param beanId
     * @return
     */
    public Observable<GiveLikeBean> findByBeanIdRxJava(int beanId) {
        return Observable.create(new ObservableOnSubscribe<GiveLikeBean>() {
            @Override
            public void subscribe(ObservableEmitter<GiveLikeBean> emitter) throws Exception {
                GiveLikeBean giveLikeBean = findByBeanId(beanId);
                if (giveLikeBean == null) {
                    emitter.onComplete();
                } else {
                    emitter.onNext(giveLikeBean);
                }
            }
        }).compose(new RxSchedulerTransformer<>());
    }


    public void save(int id, int type, int isLike, int businessUserId) {
        GiveLikeBean giveLikeBean = GiveLikeModel.getInstance().findByBeanId(id);
        if (giveLikeBean == null) {
            giveLikeBean = new GiveLikeBean(id, type, isLike, businessUserId);
            giveLikeBean.save();
        } else {
            if (isLike == 0) {
                giveLikeBean.delete();
            } else {
                giveLikeBean.setIsLike(isLike);
                giveLikeBean.update();
            }
        }
    }


}
